package com.example.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.Toast;

import com.example.App;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;

import static com.example.App.getAllFragment;

/**
 * 董建业  时间:2017/4/9.
 */

public abstract class BaseActivity extends AppCompatActivity {
    private static Boolean isExit = false;
    private boolean aReturn;

    //
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getlayoutid());
        ButterKnife.bind(this);
        initview();
        requestdata();
        viewbehavior();
    }

    public abstract int getlayoutid();

    protected abstract void initview();

    protected abstract void requestdata();

    protected abstract void viewbehavior();

    protected abstract void gobackfragment(Fragment fragment);

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isreturn();
        }
        return false;
    }

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 500);
        } else {
            finish();
            System.exit(0);
        }
    }

    public  void isreturn() {
        if (getAllFragment().size()>1){
            getAllFragment().remove(getAllFragment().size()-1);
            gobackfragment(getAllFragment().get(getAllFragment().size()-1));

        }else {
            exitBy2Click();
        }
    }
}
